package com.snoob.springCloudGateway.rateLimiter.sentinelApi;

import com.alibaba.csp.sentinel.adapter.gateway.common.SentinelGatewayConstants;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiDefinition;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiPathPredicateItem;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiPredicateItem;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.GatewayApiDefinitionManager;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager;
import com.alibaba.csp.sentinel.adapter.gateway.sc.SentinelGatewayFilter;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.csp.sentinel.adapter.gateway.sc.exception.SentinelGatewayBlockExceptionHandler;
import com.snoob.springcloudalibaba.base.BaseResult;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.reactive.result.view.ViewResolver;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.PostConstruct;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Description: TODO 基于Sentinel进行限流是通过Filter实现的。需要向容器中注入SentinelGatewayFilter过滤器和SentinelGatewayBlockExceptionHandler异常回调
 * @Author: lixing
 * @Date: 2020/11/21 15:40
 */
//@Configuration
public class RequestRateLimiterForGatewaySentinelApiConfig {
    private final List<ViewResolver> viewResolverList;
    private final ServerCodecConfigurer serverCodecConfigurer;

    public RequestRateLimiterForGatewaySentinelApiConfig(ObjectProvider<List<ViewResolver>> viewResolverListProvider, ServerCodecConfigurer serverCodecConfigurer) {
        this.viewResolverList = viewResolverListProvider.getIfAvailable(Collections::emptyList);
        this.serverCodecConfigurer = serverCodecConfigurer;
    }

    // 初始化 SentinelGatewayFilter 过滤器
    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public GlobalFilter sentinelGatewayFilter() {
        return new SentinelGatewayFilter();
    }

    // 初始化 SentinelGatewayBlockExceptionHandler 限流异常处理器
    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() {
        return new SentinelGatewayBlockExceptionHandler(viewResolverList, serverCodecConfigurer);
    }

    // 自定义限流异常页面
    @PostConstruct
    public void initBlockHandlers() {
        BlockRequestHandler blockRequestHandler = new BlockRequestHandler() {
            @Override
            public Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange, Throwable throwable) {
                return ServerResponse.status(HttpStatus.OK).
                        contentType(MediaType.APPLICATION_JSON).
                        body(BodyInserters.fromValue(new BaseResult<String>().fail("自定义路由API维度-触发流控")));
            }
        };
        GatewayCallbackManager.setBlockHandler(blockRequestHandler);
    }

    // 自定义API分组
    @PostConstruct
    public void initCustomizedApis() {
        Set<ApiDefinition> apiDefinitionSet = new HashSet<>();

        /**
         * 自定义 apiAuth_group1 分组 /springCloudGateway/auth/
         */
        ApiDefinition apiAuth_group1 = new ApiDefinition("apiAuth_group1").setPredicateItems(new HashSet<ApiPredicateItem>(){
            {
                // 添加断言，该值的内容为：配置文件spring.cloud.gateway.routes.predicates的值 + 自定义规则
                add(new ApiPathPredicateItem().setPattern("/springCloudGateway/auth/demo/requestRateLimiter1/**").setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX));
            }
        });

        /**
         * 自定义 apiAuth_group2 分组 /springCloudGateway/auth/
         */
        ApiDefinition apiAuth_group2 = new ApiDefinition("apiAuth_group2").setPredicateItems(new HashSet<ApiPredicateItem>(){
            {
                // 添加断言，该值的内容为：配置文件spring.cloud.gateway.routes.predicates的值 + 自定义规则
                add(new ApiPathPredicateItem().setPattern("/springCloudGateway/auth/demo/requestRateLimiter2/test1"));
                add(new ApiPathPredicateItem().setPattern("/springCloudGateway/auth/demo/requestRateLimiter2/test2"));
            }
        });
        //
        apiDefinitionSet.add(apiAuth_group1);
        apiDefinitionSet.add(apiAuth_group2);
        GatewayApiDefinitionManager.loadApiDefinitions(apiDefinitionSet);
    }

    // 配置初始化限流参数
    @PostConstruct
    public void initGatewayRules() {
        Set<GatewayFlowRule> gatewayFlowRuleSet = new HashSet<>();
        // 添加 apiAuth_group1分组 限流规则
        gatewayFlowRuleSet.add(new GatewayFlowRule(("apiAuth_group1")).setCount(1).setIntervalSec(1));
        // 添加 apiAuth_group2分组 限流规则
        gatewayFlowRuleSet.add(new GatewayFlowRule(("apiAuth_group2")).setCount(1).setIntervalSec(1));
        //
        GatewayRuleManager.loadRules(gatewayFlowRuleSet);
    }

}
